package com.agger.eurekaclientuserservice.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @classname: DruidConfig
 * @description: druid数据源配置
 * @author chenhx
 * @date 2020-07-16 15:02:04
 */
@Configuration
public class DruidConfig {

    //引入配置文件中相关druid的配置，否则不起作用
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druid(){
        return new DruidDataSource();
    }

    //配置druid的监控
    /**
     * @Title: statViewServlet
     * @Description:  配置一个管理后台的Servlet
     * @return org.springframework.boot.web.servlet.ServletRegistrationBean
     * @author chenhx
     * @date 2019-09-26 14:40:08
     */
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean <StatViewServlet> bean = new ServletRegistrationBean <>(new StatViewServlet(), "/druid/*");
        Map<String,String> map = new HashMap();
        map.put("loginUsername","admin");
        map.put("loginPassword","111111");
        //允许访问
        map.put("allow","localhost");
        //拒绝访问
        map.put("deny","192.168.16.110");

        bean.setInitParameters(map);
        return bean;
    }

    /**
     * @Title: webStatFilter
     * @Description:   注册web监控的filter
     * @return org.springframework.boot.web.servlet.FilterRegistrationBean
     * @author chenhx
     * @date 2019-09-26 14:46:14
     */
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String,String> map = new HashMap();
        map.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(map);
        bean.setUrlPatterns(Collections.singletonList("/*"));

        return bean;
    }
}
